using System;
using System.Windows;
using AdRotatorXNA;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;

#if WINDOWS_RT
using Windows.UI.Xaml;
#endif

namespace AdRotatorExampleXNA
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            Application.Current.UnhandledException += Current_UnhandledException;

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

#if WINDOWS_RT
            // For Metro we default to the native resolution of the window.
            graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
            graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
#else

            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;
#endif

#if !WINDOWS_RT
            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);
            graphics.IsFullScreen = true;
#endif

            Window.OrientationChanged += new EventHandler<EventArgs>(Window_OrientationChanged);
            graphics.SupportedOrientations = DisplayOrientation.Portrait |
                DisplayOrientation.LandscapeLeft |
                DisplayOrientation.LandscapeRight;
        }

        protected override void OnActivated(object sender, EventArgs args)
        {
#if !WINDOWS_RT
            try
            {
                LittleWatson.CheckForPreviousException("adrotator@xna-uk.net", "AdRotator XNA Example Error Report");
            }
            catch { } 
#endif
            base.OnActivated(sender, args);
        }

        #if WINDOWS_PHONE
        private void Current_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
#else
        private void Current_UnhandledException(object sender, UnhandledExceptionEventArgs e)
#endif
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
#if !WINDOWS_RT
            else
            {
                try
                {
                    LittleWatson.ReportException((Exception)e.ExceptionObject, "AdRotator XNA Error");
                }
                catch { }
            }
#endif
        }

        void Window_OrientationChanged(object sender, EventArgs e)
        {
            //switch (Window.CurrentOrientation)
            //{
            //    case DisplayOrientation.Portrait:
            //        AdRotatorXNAComponent.Current.AdPosition = new Vector2(0, 0);
            //        break;
            //    default:
            //        AdRotatorXNAComponent.Current.AdPosition = new Vector2((GraphicsDevice.Viewport.Width / 2) - 240,0);
            //        break;
            //}
            //AdRotatorXNAComponent.Current.UpdateAdPostition();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // Add the URL to your settings file.
            AdRotatorXNAComponent.Initialize(this, "http://mysite.com/defaultAdSettings.xml");

            //Event handler to do something should the user click on your Default House Ad
            AdRotatorXNAComponent.Current.DefaultHouseAdClick += Current_DefaultHouseAdClick;

            //Optionally specify the slide (popup) direction for the Ad
            AdRotatorXNAComponent.Current.SlidingAdDirection = SlideDirection.Bottom;

            //Add the control to the XNA Component list which will display the ad
            //Note as this is XNA be sure to just to this for the game states you want it shown.
            Components.Add(AdRotatorXNAComponent.Current);

            var vp = GraphicsDevice.Viewport;
            //Specify where you want the Ad to display (based on the top left corner of the Ad)
            AdRotatorXNAComponent.Current.Enable(new Rectangle(0, vp.Height - 90, 728, 90), "AdGroupID");

            base.Initialize();
        }

        void Current_DefaultHouseAdClick()
        {
            var message = "You clicked on my Ad, thanks very much";

            try
            {
#if WINDOWS_RT
                var dialog = new Windows.UI.Popups.MessageDialog(message);

                dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK", null));

                dialog.DefaultCommandIndex = 0;
                dialog.ShowAsync().AsTask();
#else
                MessageBox.Show(message);
#endif
            }
            catch { }
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            AdRotatorXNAComponent.Current.TouchState = TouchPanel.GetState();

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }


    }
}
